package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.utils.TransferIdUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

	@Autowired
	private MemberDao memberDao;

  	@Transactional
	@Override
	public void saveOrEdit(String telephone) {
		// 根据手机号获取会员信息
		Member member = memberDao.findByTelephone(telephone);
		if( member == null){
			// 不是会员，自动注册
			member = new Member();
			member.setPhoneNumber(telephone);
			member.setRegTime(new Date());
			// 调用Service保存会员
			memberDao.add(member);
		}
	}

	@Override
	@Transactional
	public Map<String, Integer> getMemberSex(){
		//从数据查询身份证号
		List<String> idS=memberDao.findMemberId();
		//存放member的容器
		List<Member> members=new ArrayList<>();
		int manCount=0; //男性会员
		int girlCount=0;//女性会员
		int idNullCount=0;//信息不全会员
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (String id : idS) {
			Member member = new Member();
			if (id!= null && id.length()==15){
				member.setIdCard(id);
				//转换为18位身份证
				String id18= TransferIdUtils.get18Ic(id);
				//获取性别
				String sex = TransferIdUtils.getSex(id18);
				member.setSex(sex);
				if (sex.equals("1")){
					manCount++;
				}else {
					girlCount++;
				}
				//获取生日
				String birthday = TransferIdUtils.getBirthday(id18);

					//转换生日格式并赋值给member
				try {
					member.setBirthday(sdf.parse(birthday));
				} catch (ParseException e) {
					e.printStackTrace();
				}

			}else if (id!=null && id.length()==18){
				member.setIdCard(id);
				//获取性别
				String sex = TransferIdUtils.getSex(id);
				member.setSex(sex);
				if (sex.equals("1")){
					manCount++;
				}else {
					girlCount++;
				}

				//获取生日
				String birthday = TransferIdUtils.getBirthday(id);
				try {
					//转换生日格式并赋值给member
					member.setBirthday(sdf.parse(birthday));
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}else {
				//为空值,信息未完善的
				idNullCount++;
			}

			members.add(member);
		}

		//封装数据
		Map<String,Integer> map=new HashMap<>();
		map.put("男",manCount);
		map.put("女",girlCount);
		map.put("信息未完善",idNullCount);
		log.debug("map==============>"+map);

		//更新数据库信息,有身份证的才更新
		log.debug("members==========="+members);
		/*for (Member member : members) {
			memberDao.editMemberByIdCard(member);
		}*/
		return map;
	}
    @Override
    public List<String> getMemberIDNum() {
        return memberDao.getMemberIDNum();
    }

	@Override
	public Integer getMemberNum() {
		return memberDao.getMemberNum();
	}

	@Override
	public Map<String, Object> getMemberReport() {
		List<String> months = getMonthOfLastYear();
		List<Long> memberCount = new ArrayList<>();
		//统计每个月份对应的会员数量
		for (String month : months) {
            long count = getMemerCountOfMonth(month);
			memberCount.add(count);
		}
		Map<String,Object> map = new HashMap<>();
		map.put("months", months);
		map.put("memberCount", memberCount);

		return map;
	}

	@Override
	public Map<String, Object> getMemberReportByDate(String startDate, String endDate) {

		List<String> months = new ArrayList<>();
		//获取所选择时间段内的所有月份
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

		try {
			Date date1 = sdf.parse(startDate);
			//通过循环 添加数据到集合
			while (!sdf.format(date1).equals(endDate)){
				months.add(sdf.format(date1));
				date1.setMonth(date1.getMonth()+1);
			}
			months.add(endDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		List<Long> memberCount = new ArrayList<>();
		//统计每个月份对应的会员数量
		for (String month : months) {
            long count = getMemerCountOfMonth(month);
            memberCount.add(count);
		}

		//封装数据
		Map<String,Object> map = new HashMap<>();
		map.put("months", months);
		map.put("memberCount", memberCount);

		log.debug("map========="+map);
		return map;
	}

	private long getMemerCountOfMonth(String month){
		String firstDay = month +  "-01";
		String lastDay = getThisMonthLastDay(firstDay);
		long count = memberDao.findCountBeforeByDate(lastDay);
		return count;
	}

	private String getThisMonthLastDay(String firstDay){
		//2020-02-01 thisMonthFirstDay
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date firstDate = sdf.parse(firstDay);
			//创建日历对象
			Calendar cal = Calendar.getInstance();
			//设置为本月一号
			cal.setTime(firstDate);
			//调整为下月1号
			cal.add(Calendar.MONTH, 1);
			//调整为前一天(本月的最后一天)
			cal.add(Calendar.DAY_OF_MONTH, -1);

			String str = sdf.format(cal.getTime());
			return str;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取最近一年的月份
	 * @return
	 */
	public List<String> getMonthOfLastYear(){
		List<String> months = new ArrayList<>();
		//获取前12个月份
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -12);
		for (int i = 0; i < 12; i++) {
			calendar.add(Calendar.MONTH, 1);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
			String date = simpleDateFormat.format(calendar.getTime());
			months.add(date);
		}
		return months;
	}
}